package com.ja.openchat.ui.message.adapter;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.ChatDraftManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.ComplexSpannableStringUtils;
import com.zy.openchat.util.DateHelper;
import com.ja.openchat.views.UserAvatarView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.zy.openchat.activity.chat
 * @ClassName: HistoryMessageListAdapter
 * @Description: 会话列表适配器
 */
public class RecentMessageListAdapter extends BaseQuickAdapter<ChatInfo, BaseViewHolder> {

    private HashMap<Long, SuperGroupInfo> superGoupInfos = new HashMap<>();

    public SuperGroupInfo getSuperGroupByChatId(final ChatInfo chatInfo){
        if(chatInfo==null||!chatInfo.isSuperGroup()){
            return null;
        }
        if(superGoupInfos.get(chatInfo.id)!=null){
            return superGoupInfos.get(chatInfo.id);
        }
        TelegramManager.getTelegramManager().getSuperGroupInfo(getContext(), chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                putSuperGroupInfo(chatInfo.id,obj);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
        return null;
    }

    public void putSuperGroupInfo(long chatId,SuperGroupInfo obj){
        if(obj==null){
            return;
        }
        superGoupInfos.put(chatId,obj);
        int length = getData().size();
        for(int i = 0;i<length;i++){
            if(getItem(i).id == chatId){
                RecyclerView recyclerView = getRecyclerView();
                if(recyclerView!=null&&recyclerView instanceof SwipeRecyclerView){
                    ((SwipeRecyclerView)recyclerView).getOriginAdapter().notifyItemChanged(i);
                }
                break;
            }
        }
    }

    public void notifyChat(ChatInfo chatInfo){
        if(chatInfo==null||Common.isEmpty(getData())){
            return;
        }
        int length = getData().size();
        for(int i = 0;i<length;i++){
            ChatInfo chat = getItem(i);
            if(chat.chatId() == chatInfo.id){
                notifyItemChanged(i);
                break;
            }
        }
    }

    public RecentMessageListAdapter(int layoutResId, @Nullable List<ChatInfo> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, ChatInfo chat) {
        UserAvatarView avatarView = helper.getView(R.id.iv_icon);
        avatarView.setTextSize(20);
        //待补充本地头像
        if (chat.isGroup()) {//群组

            helper.setTextColor(R.id.iv_title, ContextCompat.getColor(getContext(), R.color.black));
            helper.setGone(R.id.secret_icon, true);
            //群组名称
            helper.setText(R.id.iv_title, chat.title);
            //群组头像
            avatarView.showGroup(chat);
        } else {//单聊
            //对方昵称
            helper.setTextColor(R.id.iv_title, ContextCompat.getColor(getContext(), !chat.isSecretChat() ? R.color.black : R.color.colorAccent));
            helper.setGone(R.id.secret_icon, !chat.isSecretChat());
            helper.setText(R.id.iv_title, UserInfo.userDisplayName(chat.userId()));
            //
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(chat.userId());
            if (user != null) {
                avatarView.showUser(user);
            } else {
                avatarView.showName(UserInfo.userDisplayName(chat.userId()));
            }
        }

        //内容设置
        TextView timeText = helper.getView(R.id.tv_time);
        if (chat.lastMessage != null) {
            if (chat.isSecretChat()) {
                helper.setText(R.id.tv_content, "*********");
            } else {
                String content = ChatDraftManager.getInstance().getChatDraftContent(chat.id);
                //内容
                if (!TextUtils.isEmpty(content)) {
                    helper.setText(R.id.tv_content, ComplexSpannableStringUtils
                            .getBuilder(String.format("[%s]",getContext().getString(R.string.draft_text)))
                            .setForegroundColor(ContextCompat.getColor(getContext(), R.color.CG2))
                            .append(content)
                            .create());
                } else {
                    if (chat.isGroup()) {
                        String innerContent = chat.lastMessage.toString();
                        UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(chat.lastMessage.sender_user_id());
                        if (user != null && !chat.lastMessage.isOutgoing() && !chat.lastMessage.isTipMessage()) {
                            String nickName = TelegramManager.getTelegramManager().getTgData().getGroupNickName(chat.chatId(), chat.lastMessage.sender_user_id());
                            innerContent = String.format("%s:%s", TextUtils.isEmpty(nickName)?user.displayName():nickName, innerContent);
                            if (chat.unread_mention_count > 0) {
                                helper.setText(R.id.tv_content, ComplexSpannableStringUtils
                                        .getBuilder(String.format("[%s]",getContext().getString(R.string.someone_at_me)))
                                        .setForegroundColor(ContextCompat.getColor(getContext(), R.color.CG2))
                                        .append(innerContent).create());
                            } else {
                                helper.setText(R.id.tv_content, innerContent);
                            }
                        } else {
                            helper.setText(R.id.tv_content, innerContent);
                        }
                    } else {
                        helper.setText(R.id.tv_content, chat.lastMessage.toString());
                    }
                }
            }
            //时间
            timeText.setText(DateHelper.getMessageFullDisplayTime(chat.modifyDate() * 1000, false));
            //已读未读角标
            ImageView readImageView = helper.getView(R.id.iv_unread);
            if (chat.lastMessage.isOutgoing() && chat.lastMessage.canShowReadFlag()) {
                readImageView.setVisibility(View.VISIBLE);
                readImageView.setImageResource(chat.lastMessage.isRead() ? R.mipmap.image_message_read : R.mipmap.image_message_unread);
            } else {
                readImageView.setVisibility(View.GONE);
            }
            //消息状态
            if (chat.lastMessage.sendState() == TelegramManager.MessageSendState.MessageSendState_Success) {
                helper.setGone(R.id.indicatorView, true);
                helper.setGone(R.id.failView, true);
            } else {
                if (chat.lastMessage.sendState() == TelegramManager.MessageSendState.MessageSendState_Fail) {
                    helper.setGone(R.id.indicatorView, true);
                    helper.setGone(R.id.failView, false);
                } else {
                    helper.setGone(R.id.indicatorView, false);
                    helper.setGone(R.id.failView, true);
                }
            }
        } else {
            helper.setText(R.id.tv_content, " ");
            timeText.setText(" ");
            timeText.setCompoundDrawables(null, null, null, null);
            helper.setGone(R.id.indicatorView, true);
            helper.setGone(R.id.failView, true);
        }

        //未读角标
        helper.setGone(R.id.tv_unread, chat.unread_count <= 0);
        helper.setText(R.id.tv_unread, chat.unread_count > 99 ? "99+" : ("" + chat.unread_count));

        //提醒设置
        if (chat.default_disable_notification) {
            helper.setGone(R.id.muteView, false);
        } else {
            helper.setGone(R.id.muteView, true);
        }

        //置顶设置
        if (chat.is_pinned) {//置顶
            helper.setBackgroundColor(R.id.rootView, Color.parseColor("#f5f5f5"));
        } else {
            helper.setBackgroundColor(R.id.rootView, Color.WHITE);
        }
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, ChatInfo chat, @NonNull List<?> payloads) {
        if(!Common.isEmpty(payloads)&&payloads.get(0) instanceof Integer){
            int type = (Integer)payloads.get(0);

            if(type == Constants.Notify_User_Name_Type){
                if (chat.lastMessage != null&&chat.isGroup()) {
                    String nickName = TelegramManager.getTelegramManager().getTgData().getGroupNickName(chat.chatId(), chat.lastMessage.sender_user_id());
                    if(!TextUtils.isEmpty(nickName)){
                        helper.setText(R.id.tv_content, String.format("%s:%s", nickName, chat.lastMessage.toString()));
                    }
                }
            }
        }
    }
}
